<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>手写Promise | Jaho’s Blog</title>
    <meta name="generator" content="VuePress 1.8.0">
    <link rel="icon" href="/favicon.ico">
    <link rel="manifest" href="/manifest.json">
    <meta name="description" content="记录日常学习工作">
    
    <link rel="preload" href="/assets/css/0.styles.5b8fe0a4.css" as="style"><link rel="preload" href="/assets/js/app.6514719e.js" as="script"><link rel="preload" href="/assets/js/2.ea114ffb.js" as="script"><link rel="preload" href="/assets/js/26.39392f70.js" as="script"><link rel="preload" href="/assets/js/4.e093c564.js" as="script"><link rel="prefetch" href="/assets/js/10.13203aa5.js"><link rel="prefetch" href="/assets/js/11.099868c4.js"><link rel="prefetch" href="/assets/js/12.c8365e17.js"><link rel="prefetch" href="/assets/js/13.89751e7c.js"><link rel="prefetch" href="/assets/js/14.31f563eb.js"><link rel="prefetch" href="/assets/js/15.08b381b6.js"><link rel="prefetch" href="/assets/js/16.1a3867de.js"><link rel="prefetch" href="/assets/js/17.7dd4e0c6.js"><link rel="prefetch" href="/assets/js/18.907c4597.js"><link rel="prefetch" href="/assets/js/19.fac8aa1a.js"><link rel="prefetch" href="/assets/js/20.73fe0e75.js"><link rel="prefetch" href="/assets/js/21.5c50aa1c.js"><link rel="prefetch" href="/assets/js/22.83d03663.js"><link rel="prefetch" href="/assets/js/23.061e7ac0.js"><link rel="prefetch" href="/assets/js/24.cc7e9011.js"><link rel="prefetch" href="/assets/js/25.fa6c7aef.js"><link rel="prefetch" href="/assets/js/27.204436be.js"><link rel="prefetch" href="/assets/js/28.3f54c157.js"><link rel="prefetch" href="/assets/js/29.799d048c.js"><link rel="prefetch" href="/assets/js/3.6c5d6214.js"><link rel="prefetch" href="/assets/js/30.deed02f3.js"><link rel="prefetch" href="/assets/js/31.5916873b.js"><link rel="prefetch" href="/assets/js/32.b0634144.js"><link rel="prefetch" href="/assets/js/33.734675b8.js"><link rel="prefetch" href="/assets/js/34.20404dc4.js"><link rel="prefetch" href="/assets/js/35.d93b829f.js"><link rel="prefetch" href="/assets/js/36.b0692d8d.js"><link rel="prefetch" href="/assets/js/37.3dffa306.js"><link rel="prefetch" href="/assets/js/38.04649a97.js"><link rel="prefetch" href="/assets/js/39.7dfcdc32.js"><link rel="prefetch" href="/assets/js/40.04914511.js"><link rel="prefetch" href="/assets/js/41.ced85449.js"><link rel="prefetch" href="/assets/js/42.72739213.js"><link rel="prefetch" href="/assets/js/43.de1cff16.js"><link rel="prefetch" href="/assets/js/44.48e301ae.js"><link rel="prefetch" href="/assets/js/45.870a7650.js"><link rel="prefetch" href="/assets/js/46.657f15b8.js"><link rel="prefetch" href="/assets/js/47.3df1bfdb.js"><link rel="prefetch" href="/assets/js/48.f4e4e774.js"><link rel="prefetch" href="/assets/js/49.632bf611.js"><link rel="prefetch" href="/assets/js/5.6531e181.js"><link rel="prefetch" href="/assets/js/50.a8018493.js"><link rel="prefetch" href="/assets/js/51.cb424f59.js"><link rel="prefetch" href="/assets/js/52.a9f595dc.js"><link rel="prefetch" href="/assets/js/53.cf8a9ec0.js"><link rel="prefetch" href="/assets/js/54.46d774a3.js"><link rel="prefetch" href="/assets/js/55.3574f9b8.js"><link rel="prefetch" href="/assets/js/56.baf60ba5.js"><link rel="prefetch" href="/assets/js/57.af42b559.js"><link rel="prefetch" href="/assets/js/58.9300cb59.js"><link rel="prefetch" href="/assets/js/6.00f437ec.js"><link rel="prefetch" href="/assets/js/7.58ac7166.js"><link rel="prefetch" href="/assets/js/8.1b9c5002.js"><link rel="prefetch" href="/assets/js/9.5c076362.js">
    <link rel="stylesheet" href="/assets/css/0.styles.5b8fe0a4.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/logo.png" alt="Jaho’s Blog" class="logo"> <span class="site-name can-hide">Jaho’s Blog</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/posts/" class="nav-link router-link-active">
  技术博客
</a></div> <a href="https://juejin.cn/user/26836627369806" target="_blank" rel="noopener noreferrer" class="repo-link">
    个人主页
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/posts/" class="nav-link router-link-active">
  技术博客
</a></div> <a href="https://juejin.cn/user/26836627369806" target="_blank" rel="noopener noreferrer" class="repo-link">
    个人主页
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav>  <ul class="sidebar-links"><li><a href="/posts/" aria-current="page" class="sidebar-link">写在前面</a></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>工作问题解决</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading open"><span>JavaScript</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/posts/JavaScript/闭包作用域.html" class="sidebar-link">了解闭包及作用域</a></li><li><a href="/posts/JavaScript/短路原则.html" class="sidebar-link">布尔判定和短路原则</a></li><li><a href="/posts/JavaScript/类型转换.html" class="sidebar-link">类型转换</a></li><li><a href="/posts/JavaScript/数组转树.html" class="sidebar-link">数组转树方案</a></li><li><a href="/posts/JavaScript/数组拍平.html" class="sidebar-link">数组拍平方案</a></li><li><a href="/posts/JavaScript/数组求和.html" class="sidebar-link">数组求和（不允许使用循环）</a></li><li><a href="/posts/JavaScript/async.html" class="sidebar-link">async await实战</a></li><li><a href="/posts/JavaScript/defer.html" class="sidebar-link">JS文档的解析:async、defer 属性</a></li><li><a href="/posts/JavaScript/set.html" class="sidebar-link">Set笔记</a></li><li><a href="/posts/JavaScript/map.html" class="sidebar-link">Map笔记</a></li><li><a href="/posts/JavaScript/call.html" class="sidebar-link">手写call、bind、apply</a></li><li><a href="/posts/JavaScript/eventBus.html" class="sidebar-link">Eventbus使用</a></li><li><a href="/posts/JavaScript/instanceof.html" class="sidebar-link">浅析instanceof的实现</a></li><li><a href="/posts/JavaScript/function.html" class="sidebar-link">如何优雅的用function实现一个class</a></li><li><a href="/posts/JavaScript/require.html" class="sidebar-link">浅析commonjs中require的执行方式</a></li><li><a href="/posts/JavaScript/promise.html" aria-current="page" class="active sidebar-link">手写Promise</a></li></ul></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>Css</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>Nodejs</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>Vue</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>Git</span> <span class="arrow right"></span></p> <!----></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="手写promise"><a href="#手写promise" class="header-anchor">#</a> 手写Promise</h1> <blockquote><p>对于Promise当中的一些特性，我们需要了解并且掌握，今天我们来根据特性一步一步的实现我们的Promise源码，更好的理解并且掌握它</p></blockquote> <h4 id="_1、resolve-reject-实现"><a href="#_1、resolve-reject-实现" class="header-anchor">#</a> 1、resolve reject 实现</h4> <div class="language-diff extra-class"><pre class="language-diff"><code>//html
let p = new Promise((resolve, reject) =&gt; {
<span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">   resolve('OK11');  
</span><span class="token prefix unchanged"> </span><span class="token line">   resolve('OK');  
</span><span class="token prefix unchanged"> </span><span class="token line">   //reject('rrr')
</span></span>});
console.log(p)
//js
class Promise{
<span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">   constructor(executor){
</span><span class="token prefix unchanged"> </span><span class="token line">       let _this = this
</span><span class="token prefix unchanged"> </span><span class="token line">       _this.PromiseState = 'pending' //用于保存状态
</span><span class="token prefix unchanged"> </span><span class="token line">       _this.PromiseResult = null //用于保存结果
</span><span class="token prefix unchanged"> </span><span class="token line">       let resolve = function(data){
</span><span class="token prefix unchanged"> </span><span class="token line">           _this.PromiseState = 'success'//没有使用箭头函数，this指向要改变
</span><span class="token prefix unchanged"> </span><span class="token line">           _this.PromiseResult = data
</span><span class="token prefix unchanged"> </span><span class="token line">       }
</span><span class="token prefix unchanged"> </span><span class="token line">       let reject = function(data){
</span><span class="token prefix unchanged"> </span><span class="token line">           _this.PromiseState = 'rejected'
</span><span class="token prefix unchanged"> </span><span class="token line">           _this.PromiseResult = data
</span><span class="token prefix unchanged"> </span><span class="token line">       }
</span><span class="token prefix unchanged"> </span><span class="token line">       executor(resolve,reject)
</span><span class="token prefix unchanged"> </span><span class="token line">   }
</span></span></code></pre></div><blockquote><p>一开始对于<code>executor(resolve,reject)</code>这一段不太理解，可以理解为new Promise实例化的时候传入一个函数，放到construtor中进行执行，函数需要传入俩个参数，需要用resolve和reject两个函数当做参数，这里在传入的函数中调用resolve即调用constructor中的resolve</p></blockquote> <p>来看下控制台打印结果</p> <p><img src="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0541faf9013f4f71b9a54475c91b0860~tplv-k3u1fbpfcp-watermark.image?" alt="image.png"></p> <h4 id="_2、只能改变一次状态"><a href="#_2、只能改变一次状态" class="header-anchor">#</a> 2、只能改变一次状态</h4> <blockquote><p>Promise中只能改变一次状态，所以每次改变状态前判断一下状态是否已经改变了，这个比较简单</p></blockquote> <div class="language-diff extra-class"><pre class="language-diff"><code>//html
let p = new Promise((resolve, reject) =&gt; {
<span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">   resolve('OK11');  
</span><span class="token prefix unchanged"> </span><span class="token line">   resolve('OK');  
</span></span>});
//js
let resolve = function(data){
<span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">    if(_this.PromiseState!='pending') return
</span></span><span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">    ...
</span></span>}
let reject = function(data){
<span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">    if(_this.PromiseState!='pending') return
</span></span><span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">    ...
</span></span>}
</code></pre></div><p>现在只会执行一次resolve
<img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/8687892c9dc74678a04c11eea48d14a7~tplv-k3u1fbpfcp-watermark.image?" alt="image.png"></p> <h4 id="_3、抛出错误改变"><a href="#_3、抛出错误改变" class="header-anchor">#</a> 3、抛出错误改变</h4> <blockquote><p>Promise中如果没有改变状态而是抛出错误，需要将状态改变为reject，那么我们在executor执行的时候捕获一下错误，如果有错误，改变状态</p></blockquote> <div class="language-diff extra-class"><pre class="language-diff"><code>let p = new Promise((resolve, reject) =&gt; {
<span class="token deleted-sign deleted"><span class="token prefix deleted">-</span><span class="token line">    resolve('OK11');  
</span><span class="token prefix deleted">-</span><span class="token line">    resolve('OK');  
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">    throw 'error'
</span></span>});
class Promise{
<span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">   constructor(executor){
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">        try {
</span></span><span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">           executor(resolve,reject)
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">        } catch (error) {
</span><span class="token prefix inserted">+</span><span class="token line">            reject(error)
</span><span class="token prefix inserted">+</span><span class="token line">        }
</span><span class="token prefix inserted">+</span><span class="token line">    }
</span></span></code></pre></div><p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/54625f6a2ca34c0e9dd6cc3374d86348~tplv-k3u1fbpfcp-watermark.image?" alt="image.png"></p> <h4 id="_4、then实现"><a href="#_4、then实现" class="header-anchor">#</a> 4、then实现</h4> <blockquote><p>当进入到then的时候 <code>promise同步状态下</code> 执行到then的时候状态是已经改变的，then中传入两个函数，我们根据状态的不同调用不同的函数,调用函数的时候有一个value值，</p></blockquote> <blockquote><p>这个value是执行<code>resolve('OK')</code>的时候已经将ok保存到PromiseResult中，所以在then中输出value的时候，其实就是输出PromiseResult</p></blockquote> <div class="language-diff extra-class"><pre class="language-diff"><code>//html
let p = new Promise((resolve, reject) =&gt; {
<span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">   resolve('OK');  
</span></span>});
p.then(value =&gt; {
<span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">   console.log(value)
</span></span>}, reason=&gt;{
<span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">   console.warn(reason)
</span></span>})

//js
<span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line"> then(onResolved,onRejected){
</span><span class="token prefix inserted">+</span><span class="token line">   if(this.PromiseState=='success'){
</span><span class="token prefix inserted">+</span><span class="token line">        onResolved(this.PromiseResult)
</span><span class="token prefix inserted">+</span><span class="token line">    }
</span><span class="token prefix inserted">+</span><span class="token line">    if(this.PromiseState=='rejected'){
</span><span class="token prefix inserted">+</span><span class="token line">        onRejected(this.PromiseResult)
</span><span class="token prefix inserted">+</span><span class="token line">    }
</span></span>}
</code></pre></div><p>此时我们的OK已经打印出来
<img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/975259a3fd914f6f8f717efb6a5de381~tplv-k3u1fbpfcp-watermark.image?" alt="image.png"></p> <h4 id="_5-异步调用时候then中的问题"><a href="#_5-异步调用时候then中的问题" class="header-anchor">#</a> 5.异步调用时候then中的问题</h4> <blockquote><p>以下这段代码不会输出ok，因为在then执行的时候，由于事件循环，then调用的时候resolve还未调用，所以在then中<code>PromiseState</code>的状态仍然未pending，因此不会输出，所以我们需要加一个判断</p></blockquote> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">let</span> p <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span> reject</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    <span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">=&gt;</span><span class="token punctuation">{</span>
        <span class="token function">resolve</span><span class="token punctuation">(</span><span class="token string">'OK'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span><span class="token punctuation">,</span><span class="token number">100</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
p<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token parameter">value</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>value<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token parameter">reason</span><span class="token operator">=&gt;</span><span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span>reason<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

p<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token parameter">value</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token number">2222</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token parameter">reason</span><span class="token operator">=&gt;</span><span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span>reason<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre></div><blockquote><p>对于then执行的时候状态仍未pending的状态，我们将回调存到回调列表中，<code>等待resolve调用</code>的时候再去执行所有回调，之所以用<code>数组保存</code>，因为可能有多个then回调</p></blockquote> <div class="language-diff extra-class"><pre class="language-diff"><code>constructor(executor){
<span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">    _this.callbacks = []
</span></span><span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">   let resolve = function(data){
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">        _this.callbacks.forEach((item)=&gt;{
</span><span class="token prefix inserted">+</span><span class="token line">            item.onResolve(_this.PromiseResult)
</span><span class="token prefix inserted">+</span><span class="token line">        })
</span></span><span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">   }
</span><span class="token prefix unchanged"> </span><span class="token line">   let reject = function(data){
</span></span><span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">        _this.callbacks.forEach((item)=&gt;{
</span><span class="token prefix inserted">+</span><span class="token line">            item.onReject(_this.PromiseResult)
</span><span class="token prefix inserted">+</span><span class="token line">        })
</span></span><span class="token unchanged"><span class="token prefix unchanged"> </span><span class="token line">   }
</span></span>then(onResolve,onReject){
<span class="token inserted-sign inserted"><span class="token prefix inserted">+</span><span class="token line">    if(this.PromiseState=='pending'){//处理resolved异步比then慢执行的时候
</span><span class="token prefix inserted">+</span><span class="token line">        this.callbacks.push({onResolve,onReject})
</span><span class="token prefix inserted">+</span><span class="token line">    } 
</span></span>} 
</code></pre></div><p><img src="https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/40c632209dbe4b058d01fee33b860bdd~tplv-k3u1fbpfcp-watermark.image?" alt="image.png"></p> <h4 id="实现promise的返回值"><a href="#实现promise的返回值" class="header-anchor">#</a> 实现promise的返回值</h4> <blockquote><p>如果返回值是一个<code>非promise</code>对象,返回状态设置为成功，
如果返回值是一个异常,返回状态设置为失败</p></blockquote> <blockquote><p>我们知道then中返回的也是一个Promise，所以我们给then中返回一个Promise，只需要在promise中做两件事情，执行回调，改变状态</p></blockquote> <blockquote><p>如果返回值是一个promise，此时我们的promise已经有then方法了，我们直接用then方法来处理状态的改变即可，最后加上一层try的错误检验，reject的方法相同</p></blockquote> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">let</span> p <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span> reject</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    <span class="token function">resolve</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> res <span class="token operator">=</span> p<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token parameter">value</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span>reject</span><span class="token punctuation">)</span><span class="token operator">=&gt;</span><span class="token punctuation">{</span>
        <span class="token function">resolve</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token parameter">reason</span><span class="token operator">=&gt;</span><span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span>reason<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>p<span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>res<span class="token punctuation">)</span>

<span class="token comment">//js</span>
    <span class="token function">then</span><span class="token punctuation">(</span><span class="token parameter">onResolve<span class="token punctuation">,</span>onReject</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>PromiseState<span class="token operator">==</span><span class="token string">'pending'</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>callbacks<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token punctuation">{</span>onResolve<span class="token punctuation">,</span>onReject<span class="token punctuation">}</span><span class="token punctuation">)</span>
        <span class="token punctuation">}</span> 
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span>reject</span><span class="token punctuation">)</span><span class="token operator">=&gt;</span><span class="token punctuation">{</span>
            <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>PromiseState<span class="token operator">==</span><span class="token string">'success'</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
                 <span class="token keyword">try</span> <span class="token punctuation">{</span>
                    <span class="token keyword">let</span> res <span class="token operator">=</span> <span class="token function">onResolve</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>PromiseResult<span class="token punctuation">)</span><span class="token comment">//执行回调</span>
                    <span class="token keyword">if</span><span class="token punctuation">(</span>res <span class="token keyword">instanceof</span> <span class="token class-name">Promise</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
                        res<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">v</span><span class="token punctuation">)</span><span class="token operator">=&gt;</span><span class="token punctuation">{</span><span class="token comment">//之所以加这一层 是因为promise状态改变了 但是里面的值没输出 所以要加个then，不然就成了promise里面包裹着一个pormise</span>
                            <span class="token function">resolve</span><span class="token punctuation">(</span>v<span class="token punctuation">)</span><span class="token comment">//改变状态</span>
                        <span class="token punctuation">}</span><span class="token punctuation">,</span><span class="token punctuation">(</span><span class="token parameter">r</span><span class="token punctuation">)</span><span class="token operator">=&gt;</span><span class="token punctuation">{</span>
                            <span class="token function">reject</span><span class="token punctuation">(</span>r<span class="token punctuation">)</span><span class="token comment">//改变状态</span>
                        <span class="token punctuation">}</span><span class="token punctuation">)</span>
                    <span class="token punctuation">}</span><span class="token keyword">else</span><span class="token punctuation">{</span>
                        <span class="token function">resolve</span><span class="token punctuation">(</span>res<span class="token punctuation">)</span><span class="token comment">//改变状态</span>
                    <span class="token punctuation">}</span>
                 <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span>error<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                     <span class="token function">reject</span><span class="token punctuation">(</span>error<span class="token punctuation">)</span>
                 <span class="token punctuation">}</span>  
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
</code></pre></div><p>执行一下看看</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">let</span> p <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span> reject</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    <span class="token function">resolve</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">let</span> res <span class="token operator">=</span> p<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token parameter">value</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span>reject</span><span class="token punctuation">)</span><span class="token operator">=&gt;</span><span class="token punctuation">{</span>
        <span class="token function">resolve</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token parameter">reason</span><span class="token operator">=&gt;</span><span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span>reason<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>p<span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>res<span class="token punctuation">)</span>
</code></pre></div><p>如果没有判断<code>res instanceof Promise</code> ，第二个then的会输出一个promise</p> <img src="https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/1efa847093ca4582a8d1cd0c145beca7~tplv-k3u1fbpfcp-watermark.image?" alt="image.png" width="70%"> <p>加上判断后的结果</p> <img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/fed10f22712b44719ea38ac7bd2d854f~tplv-k3u1fbpfcp-watermark.image?" alt="image.png" width="70%"> <p>一开始我在判断返回值为promise这个地方一直搞不懂，为啥要执行then，为啥调用resolve,所以在写源码的时候应该多动手打印、debugger输出,下面是我对这段代码的解释</p> <div class="language-js extra-class"><pre class="language-js"><code><span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Promise</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">resolve<span class="token punctuation">,</span>reject</span><span class="token punctuation">)</span><span class="token operator">=&gt;</span><span class="token punctuation">{</span>
<span class="token operator">...</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span>result <span class="token keyword">instanceof</span> <span class="token class-name">Promise</span><span class="token punctuation">)</span> <span class="token punctuation">{</span><span class="token comment">//如果是 Promise 类型的对象</span>
    result<span class="token punctuation">.</span><span class="token function">then</span><span class="token punctuation">(</span><span class="token parameter">v</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
        <span class="token comment">//之所以加这一层 是以为result是一个promise，</span>
        <span class="token comment">// 他的成功和失败决定了外层promise的状态（也就是真正then返回的promise）</span>
        <span class="token comment">//那么他成功 则调用外层的成功</span>
        <span class="token function">resolve</span><span class="token punctuation">(</span>v<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token parameter">r</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
        <span class="token function">reject</span><span class="token punctuation">(</span>r<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><p><em><strong>本文正在参加<a href="https://juejin.cn/post/7162096952883019783" title="https://juejin.cn/post/7162096952883019783" target="_blank" rel="noopener noreferrer">「金石计划 . 瓜分6万现金大奖」<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></strong></em></p></div> <footer class="page-edit"><!----> <div class="last-updated"><span class="prefix">上次更新:</span> <span class="time">2023-01-04 10:56:12</span></div></footer> <div class="page-nav"><p class="inner"><span class="prev">
      ←
      <a href="/posts/JavaScript/require.html" class="prev">
        浅析commonjs中require的执行方式
      </a></span> <span class="next"><a href="/posts/Css/css变量实践.html">
        css变量实践
      </a>
      →
    </span></p></div> </main></div><div class="global-ui"><!----><!----></div></div>
    <script src="/assets/js/app.6514719e.js" defer></script><script src="/assets/js/2.ea114ffb.js" defer></script><script src="/assets/js/26.39392f70.js" defer></script><script src="/assets/js/4.e093c564.js" defer></script>
  </body>
</html>
